package com.zh.harmony.mvvmharmony.util;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

public class PreferencesUtil {
    /**
     * Preferences文件名
     */
    private static final String PREFERENCES_FILE_NAME = "app_preferences";

    private static volatile Preferences mPreferences;

    private PreferencesUtil() {
    }

    /**
     * 存储一个String类型的数据
     */
    public static void putString(String key, String value) {
        Preferences preferences = getPreferences();
        preferences.putString(key, value);
        preferences.flush();
    }

    /**
     * 获取一个String类型的数据
     */
    public static String getString(String key, String defaultValue) {
        Preferences preferences = getPreferences();
        return preferences.getString(key, defaultValue);
    }

    /**
     * 获取Preferences实例
     */
    private static Preferences getPreferences() {
        if (mPreferences == null) {
            synchronized (PreferencesUtil.class) {
                if (mPreferences == null) {
                    //原生的Preferences
                    Context context = ContextUtil.getContext();
                    DatabaseHelper databaseHelper = new DatabaseHelper(context);
                    mPreferences = databaseHelper.getPreferences(PREFERENCES_FILE_NAME);
                }
            }
        }
        return mPreferences;
    }
}